package cn.read;

import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;

public class ReadFile {
    private static BufferedReader bf = null;
    private static int featureNum = 0;

//    public static void main(String[] args) throws IOException {
//        for (int i = 0; i < 1000; i++) {
//            System.out.println(getFeatureNum("wine"));
//        }
//    }

    /**
     * 得到数据集的特征数
     *
     * @param name 训练集名称
     * @return 训练集特征数
     */
    public static int getFeatureNum(String name) throws IOException {
        if (bf == null) {
            bf = new BufferedReader(new FileReader(ResourceUtils.getFile("classpath:dataset\\Alltra--" + name)));
            String[] num = bf.readLine().split(" ");
            String LastFeature = num[num.length - 1].split(":")[0];
            featureNum = Integer.parseInt(LastFeature);
        }
        return featureNum;
    }

    //按照输入的选择特征号将指定路径的文件数据拷贝到另一个测试文件
    public void getFile(List<?> choose, String path, String type) throws IOException {
        File f = new File(type);
        if (f.isFile()) {
            f.delete();
        }
        f.createNewFile();
        bf = new BufferedReader(new FileReader(path));
        PrintWriter pw = new PrintWriter(new FileOutputStream(type, true));
        while (true) {
            String data = bf.readLine();
            if (data == null || data.equals("")) {
                break;//如果行数据为空则结束
            }
            String[] dataSet = data.split(" ");//将行数据按空格分为数组
            pw.write(dataSet[0] + " ");
            for (Object o : choose) {
                int jud = 0;
                for (int i = 1; i < dataSet.length; i++) {
                    String[] ele = dataSet[i].split(":");
                    if (ele[0].equals(o)) {
                        pw.write(dataSet[i] + " ");
                        jud = 1;
                    }
                }
                if (jud == 0) {
                    pw.write(o + ":0 ");
                }
            }
            pw.write("\r\n");
            pw.flush();

        }
        bf.close();
        pw.close();
    }


}
